package cn.xm.basic.interceptor;

import cn.xm.basic.aop.PreAuthorize;
import cn.xm.basic.jwt.JwtUtils;
import cn.xm.basic.jwt.Payload;
import cn.xm.basic.jwt.RsaUtils;
import cn.xm.basic.jwt.UserInfo;
import cn.xm.org.domain.Employee;
import cn.xm.org.mapper.EmployeeMapper;
import cn.xm.user.domain.Logininfo;
import cn.xm.user.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 获取token
        String token = request.getHeader("token");
        // 判断token是否存在
        if (StringUtils.isNotBlank(token)) {
            // 判断logininfo是否存在
//            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
            // 2 解析token里面内容
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            Payload<UserInfo> userInfoPayload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = userInfoPayload.getUserInfo();
            if (userInfo.getLogininfo() != null) {
                // 如果是后台人员则需要判断权限 employee:findAll
                if (userInfo.getLogininfo().getType() == 0) {
                    // 获取到当前请求访问的方法
                    HandlerMethod method = (HandlerMethod) handler;
                    // 获取到方法上的注解
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    // 有些方法没有注解
                    if (annotation != null) {
                        // 获取注解配置的sn
                        String sn = annotation.sn();
                        // 用Logininfoid从权限表查当前用户的权限，判断是否有权访问当前接口
//                    List<String> sns = employeeMapper.findByLogininfoId(logininfo.getId());
                        List<String> sns = userInfo.getPermission();
                        // 无权则返回nopermission给后置拦截器
                        if (!sns.contains(sn)) {
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                    // 有权或不是后台则都放行
                }
                // 存在则重置过期时间，并放行
//                redisTemplate.expire(token,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 若token或logininfo为空则返回false,nologininfo
        // 为空 我们要返回 {"success":false,"resultObj":"nologin"}

        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
